// (C) Copyright 2009, 2010 Communications Programming, Inc.
/***************************************************************************************************************
*  Name: maxim517DA1
*
*  Description: Function to perform analog output utilizing i2c method and MAX517 chips.
*  Alternative to using PWM with RC filter.  
*
*  This routine uses the I2C1 device.  See maxim517DA2 to use the I2C2 device.
*
*  On UBW32, Pin A14 is I2C#1 SCL (clock signal) and Pin A15 is I2C#1 SDA (data stream).
*  On MAX517, SCL is pin 3, SDA is on pin 4.
*  MAX517 pins 7 and 8 are constant 5 volts, 2 is ground, 1 is output.
*  Pins 5 and 6 are AD0 and AD1, respectively, and determine address of chip with
*  binary code(0-3). High voltage (5 volts) indicates 1, low (ground) indicates 0.
*  Can use up to four MAX517 chips with one output per chip. 
*
*  Calling Parameters:
*  
*  int maxim517DA1( unsigned char port, // Integer between 0 and 3, defines which chip is to be used.
*        	 		                	//    Chip address uses two bits xx of output port hex value (0101 1xx0), 
*                                      	//    with remaining bits equal to 0x58
*                                      	//    0 corresponds to 00 (hex port 58), 3 correpsonds to 11 (hex port 5E)
*                 	unsigned char val); // digital val to be converted to analog
*                            		    //    Low of 0 corresponds to 0 volts, high of 255 corresponds to 5 volts
*
*  Returns:    2 = invalid port value
*			   1 = I2C failure
*              0 = success
*
*  Revision History:
*  Date    Who  Comments
*  ------  ---  -----------------------------------------------------------------------------------------
*  091213  RLP	Created.
*
***************************************************************************************************************/

#include "userLib.h"

int maxim517DA1( unsigned char port, // Integer between 0 and 3, defines which chip is to be used.
                               	   	 //    Chip address uses two bits xx of output port hex value (0101 1xx0), 
        		                     //    with remaining bits equal to 0x58
                		             //    0 corresponds to 00 (hex port 58), 3 correpsonds to 11 (hex port 5E)
                 unsigned char val)  // digital val to be converted to analog
                                     //    Low of 0 corresponds to 0 volts, high of 255 corresponds to 5 volts
{
	unsigned char buf[3];

	if(port > 3)                     // test for bad port
   	{
    	return 2;                    // bad port
   	}

    buf[0] = 0x58 + (port << 1);     // convert logical port 0-3 to hardware 0x58, 5A, 5c, or 5E
	buf[1] = 0;
	buf[2] = val;

	return( writeBytesI2C1(buf, 3) ); 
}
